// pages/databaseGuide/databaseGuide.js

module.exports = {
  insertRow,
  selectRow,
  deleteRow
}

function insertRow(collection, row, successCallBackFun, errorCallBackFun) {
  const db = wx.cloud.database()
  db.collection(collection).add({
    data: row,
    success: res => {
      console.log('[数据库] [新增记录成功] ', row)
      if (successCallBackFun) {
        successCallBackFun(res);
      }
    },
    fail: err => {
      console.error('[数据库] [新增记录失败] ', err)
      if (errorCallBackFun) {
        errorCallBackFun(res);
      } else {
        wx.showToast({
          icon: 'none',
          title: '新增记录失败'
        })
      }
    }
  })
}

function selectRow(collection, where, success, fail) {
  const db = wx.cloud.database();
  // 查询当前用户所有的 counters
  db.collection(collection).where(where).get({
    success: res => {
      console.log('[数据库] [查询记录成功] ', res)
      if (success) {
        success(res);
      }
    },
    fail: err => {
      console.error('[数据库] [查询记录失败] ', err)
      if (fail) {
        fail(res);
      } else {
        wx.showToast({
          icon: 'none',
          title: '查询记录失败'
        })
      }
    }
  })
}



function deleteRow(collection, row, successCallBackFun, errorCallBackFun) {
  const db = wx.cloud.database()
  db.collection(collection).deleteRow().remove({
    success: res => {
      wx.showToast({
        title: '删除成功',
      })
      this.setData({
        counterId: '',
        count: null,
      })
    },
    fail: err => {
      wx.showToast({
        icon: 'none',
        title: '删除失败',
      })
      console.error('[数据库] [删除记录] 失败：', err)
    }
  })
}